package com.molyfun.parents.activity.ask.view;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.setting.SuggestionActivity;
import com.molyfun.parents.impl.OnTopicBriefViewCallback;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.TopicBriefBean;
import com.molyfun.parents.utils.EmptyHelper;
import com.molyfun.parents.utils.StringUtils;
import com.molyfun.parents.utils.UIUtils;
import com.squareup.picasso.Picasso;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/18/16.
 */
public class TopicBriefView extends LinearLayout implements View.OnClickListener{

    protected LayoutInflater layoutInflater;

    private Context context;

    @InjectView(R.id.topic_cell_avator)
    ImageView mUserAvator;
    @InjectView(R.id.topic_cell_more)
    ImageView mMore;
    @InjectView(R.id.topic_user_name)
    TextView mUserName;
    @InjectView(R.id.topic_time)
    TextView mTime;
    @InjectView(R.id.topic_desc)
    TextView mTopicDesc;
    @InjectView(R.id.operation_view)
    TopicOperationView mTopicOperationView;
    @InjectView(R.id.topic_close)
    ImageView mTopicClose;

    private int mCurrentCategory = AskTopBar.AskBarChooseTab.BAR_HOT;

    private String topicId;
    private boolean isAuthor = false;

    private int mCurrentTopicBriefViewType = TopicBriefViewType.VIEW_MODE_BRIEF;

    public interface TopicBriefViewType{
        int VIEW_MODE_BRIEF = 1001;
        int VIEW_MODE_COMMENT = 1002;
    }


    public TopicBriefView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public TopicBriefView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TopicBriefView(Context context) {
        super(context);
        init(context, null);
    }

    private void init(Context context, AttributeSet attrs) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.widget_topic_brief, this);
        ButterKnife.inject(this);
        setOnClickListener(this);
        mMore.setOnClickListener(this);
    }

    public void initData(TopicBriefBean topicBean) {
        initData(topicBean, AskTopBar.AskBarChooseTab.BAR_HOT, TopicBriefViewType.VIEW_MODE_BRIEF);
    }

    public void initData(TopicBriefBean topicBean, int category) {
        initData(topicBean, category, TopicBriefViewType.VIEW_MODE_BRIEF);
    }

    /**
     * init view
     * @param category 是热门还是自己得，自己的不需要匿名
     */
    public void initData(TopicBriefBean topicBean, int category, int viewType) {
        if(topicBean == null){
            return;
        }
        mCurrentTopicBriefViewType = viewType;
        if(!TextUtils.isEmpty(topicBean.getUserid()) && topicBean.getUserid().equals(MFPApplication.getInstance().getUser().getId())){
            isAuthor = true;
        }
        mCurrentCategory = category;
        if(mCurrentCategory != AskTopBar.AskBarChooseTab.BAR_MINE && (!TextUtils.isEmpty(topicBean.getIsanonymous()) && topicBean.getIsanonymous().equals("1"))){
            //匿名
            mUserAvator.setImageResource(R.mipmap.ic_header_default);
            mUserName.setText("匿名");
        }else{
            if(!TextUtils.isEmpty(topicBean.getImgurl())){
                Picasso.with(getContext())
                        .load(topicBean.getImgurl())
                        .into(mUserAvator);
            }else{
                mUserAvator.setImageResource(R.mipmap.ic_header_default);
            }
            mUserName.setText(topicBean.getUsername());
        }

        topicId = topicBean.getId();
        mTopicOperationView.initData(topicBean, mCurrentCategory);

        if(mCurrentCategory == AskTopBar.AskBarChooseTab.BAR_MINE){
            if(!TextUtils.isEmpty(topicBean.getReplystatus()) && topicBean.getReplystatus().equals("0")){
                mTopicOperationView.setReplyCountRed(true);
            }else{
                mTopicOperationView.setReplyCountRed(false);
            }
        }
        if(topicBean.getCreatedatetime() != 0l){
            mTime.setText(StringUtils.formatDate(topicBean.getCreatedatetime()));
        }
        mTopicDesc.setText(topicBean.getTitle());
        if(EmptyHelper.isTrue(topicBean.getUdelflag()) && mCurrentCategory == AskTopBar.AskBarChooseTab.BAR_MINE){
            mTopicClose.setVisibility(View.VISIBLE);
        }else{
            mTopicClose.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.like_count:
                break;
            case R.id.suggestion:
                popupWindow.dismiss();
                SuggestionActivity.startActivity(getContext(), topicId);
                break;
            case R.id.delete_layout:
                popupWindow.dismiss();
                delTopic();
                break;
            case R.id.topic_cell_more:
                showPopupWindow(v);
                break;
            default:
                mTopicOperationView.setReplyCountRed(false);
//                TopicDetailActivity.startActivity(getContext(), topicId, mCurrentCategory);
                break;
        }
    }

    private void delTopic(){
        if(mCurrentTopicBriefViewType == TopicBriefViewType.VIEW_MODE_BRIEF){
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().delTopic(topicId);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if(response.body().getCode() == 200){
                        if(mOnTopicBriefViewCallback != null){
                            mOnTopicBriefViewCallback.onTopicBriefDel();
                        }
                    }else{
                        UIUtils.showToast(context, response.body().getMsg());
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {

                }
            });
        }else{
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().delComment(topicId);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if(response.body().getCode() == 200){
                        if(mOnTopicBriefViewCallback != null){
                            mOnTopicBriefViewCallback.onTopicBriefDel();
                        }
                    }else{
                        UIUtils.showToast(context, response.body().getMsg());
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {

                }
            });
        }
    }

    private OnTopicBriefViewCallback mOnTopicBriefViewCallback;

    public void setOnTopicBriefViewCallback(OnTopicBriefViewCallback onTopicBriefViewCallback){
        this.mOnTopicBriefViewCallback = onTopicBriefViewCallback;
    }

    PopupWindow popupWindow;
    private TextView mSuggestion;
    private LinearLayout mDelete;

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(context).inflate(
                R.layout.view_topic_popup_menu, null);
        mSuggestion = (TextView) contentView.findViewById(R.id.suggestion);
        mDelete = (LinearLayout) contentView.findViewById(R.id.delete_layout);
        mSuggestion.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        if(!isAuthor || mCurrentCategory == AskTopBar.AskBarChooseTab.BAR_HOT ){
            mDelete.setVisibility(View.GONE);
        }

        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.showAsDropDown(view);

    }

}